<template>
  <div class="role" style="width:99%;margin-top:-25px;">
    <!--工具栏-->
    <div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">

        <!--<el-form-item>-->
          <!--<el-input v-model="filters.menuName" placeholder="角色名"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item>-->
          <!--<kt-button :label="$t('action.search')" perms="sys:role:view" authType="primary" @click="findPage(null)"/>-->
        <!--</el-form-item>-->
          <kt-button :label="$t('action.addrole')" perms="AuthorityManagement:RoleManagement:add" type="primary"   authType="primary" @click="handleAdd" />
    </div>
    <!--表格内容栏-->
    <kt-table permsEdit="AuthorityManagement:RoleManagement:edit" role  :highlightCurrentRow="true" :stripe="false"
              :data="pageResult" :columns="columns" :showBatchDelete="false" 
              @findPage="findPage" @handleEdit="handleEdit" @handleDelete="handleDelete">
    </kt-table>
    <!-- </el-col> -->
    <!--新增编辑界面-->
    <el-dialog :title="operation?'新增':'编辑'" width="40%" :visible.sync="dialogVisible" :close-on-click-modal="false" @close="closeAdd">
      <el-form :model="dataForm"  :rules="dataFormRules" ref="dataForm" :size="size">
        <el-form-item label="ID" prop="id" v-if="false">
          <el-input v-model="dataForm.id" :disabled="true" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="dataForm.roleName" auto-complete="off" width="100%"></el-input>
        </el-form-item>
        <el-form-item label="角色类型" prop="roleType">
          <el-select style="width:100%" filterable clearable v-model="dataForm.roleType" @change="roleTypeChange">
                <el-option
                  v-for="item in roleType_option"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                ></el-option>
              </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input v-model="dataForm.description" auto-complete="off" type="textarea"></el-input>
        </el-form-item>

        <el-form-item label="配置权限" prop="authorityList"  >
          <el-button :size="size" type="primary"  style="float: left" @click="handlepower()">{{('选择权限')}}</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :size="size" @click.native="dialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button :size="size" authType="primary" @click.native="submitForm" :loading="editLoading" v-if="!dataForm.id">{{$t('action.submit')}}</el-button>
        <el-button :size="size" authType="primary" @click.native="submitFormEdit" :loading="editLoading" v-if="dataForm.id">{{$t('action.submit')}}</el-button>
      </div>
    </el-dialog>
    <!--权限列表-->
    <el-dialog class="rolemenu" :title="operation?'新增权限':'编辑权限'" width="50%" :visible.sync="power"
               :close-on-click-modal="false"    height="50%" >
      <div slot="footer">
        <div class="menu-container">
          <div class="menu-header">
            <span><B>角色菜单授权</B></span>
          </div>
          <el-tree :data="menuData" size="mini" show-checkbox node-key="id" :props="defaultProps" :model="dataForm"
                   style="width: 100%;pading-top:20px;" ref="menuTree" :render-content="renderContent"
                   v-loading="menuLoading" element-loading-text="拼命加载中" :check-strictly="true"
                   @check-change="handleMenuCheckChange" @check="setChilds">
          </el-tree>
          <div style="float:right;padding-right:15px;padding-top:4px;padding-bottom:4px;">
            <kt-button :label="$t('action.reset')" perms="AuthorityManagement:RoleManagement:edit" authType="primary" @click="resetSelection"
                       />
            <kt-button :label="$t('action.submit')" perms="AuthorityManagement:RoleManagement:edit" authType="primary" @click="submitAuthForm"
                        :loading="authLoading"/>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import KtTable from "@/views/Core/KtTable";
import KtButton from "@/views/Core/KtButton";
import TableTreeColumn from "@/views/Core/TableTreeColumn";
export default {
  components: {
    KtTable,
    KtButton,
    TableTreeColumn
  },
  data() {
    return {
      size: "small",
      // filters: {
      //   menuName: ''
      // },
      columns: [
        { type: "index", label: "序号", minWidth: 50 },
        { prop: "roleName", label: "角色名", minWidth: 120 },
        { prop: "description", label: "备注", minWidth: 120 }
      ],
      pageRequest: { pageNum: 1, pageSize: 8 },
      pageResult: {
        content: [],
        totalSize: ""
      },
      operation: false, // true:新增, false:编辑
      dialogVisible: false, // 新增编辑界面是否显示
      editLoading: false,
      power: false,
      dataFormRules: {
        menuName: [
          { required: true, message: "请输入角色名", trigger: "blur" }
        ],
        roleType: [{ required: true, message: "请输入角色类型", trigger: 'change' }]
      },

      // 新增编辑界面数据
      dataForm: {
        id: 0,
        roleName: "",
        description: "",
        authorityList: [],
        userType: 3
      },
      selectRole: {},
      menuData: [],
      menuSelections: [],
      menuLoading: false,
      authLoading: false,
      checkAll: false,
      currentRoleMenus: [],
      defaultProps: {
        children: "children",
        label: "menuName"
      },
      roleType_option: [],
      roleType: ""
    };
  },
  methods: {
    closeAdd(){
      this.roleType=''
    },
    // 获取分页数据
    findPage: function(data) {
      if (data !== null) {
        this.pageRequest = data.pageRequest;
        this.pageRequest = Object.assign({}, { authType: 3 }, this.pageRequest);
      }
      this.$api.user.optionsList({ codeType: "role_type" }).then(res => {
        this.roleType_option = res.keyValueList;
      });
      // this.pageRequest.columnFilters = {name: {name:'roleName', value:this.filters.name}}
      this.$api.role
        .queryFontRoleList(this.pageRequest)
        .then(res => {
          this.pageResult.content = res.userRoleList;
          this.pageResult.totalSize = res.total;
          this.findTreeData();
        })
        .then(data != null ? data.callback : "");
    },
    // 批量删除
    handleDelete: function(data) {
      this.$api.role.batchDelete(data.params).then(data.callback);
    },
    // 显示新增界面
    handleAdd: function() {
      this.dialogVisible = true;
      this.operation = true;
      this.$refs.menuTree.setCheckedKeys([]);
      this.dataForm = {
        id: "",
        roleName: "",
        description: "",
        authorityList: []
      };
      this.$api.user.optionsList({ codeType: "role_type" }).then(res => {
        this.roleType_option = res.keyValueList;
      });
    },
    handlepower: function() {
      this.$refs.menuTree.setCheckedKeys(this.dataForm.authorityList);
      this.power = true;
    },
    //延时函数
    // handleOpen(){
    //   setTimeout(console.log, 100, "open: "+$(".menu-container").html()) // TAG 1
    // },
    // 显示编辑界面
    handleEdit: function(params) {
      this.dialogVisible = true;
      this.operation = false;
      this.dataForm = Object.assign({}, params.row);
      this.$api.role.findRoleMenus({ roleId: params.row.id }).then(res => {
        this.dataForm.authorityList = res.userRole.checkedIdList;
        this.$refs.menuTree.setCheckedKeys(res.userRole.checkedIdList);
      });
      this.dataForm.roleType = params.row.roleType;
      this.roleType_option.forEach(Ritem => {
        if (Ritem.key == params.row.roleType) {
          this.dataForm.roleType = Ritem.value;
        }
      });
    },
    roleTypeChange(params) {
      this.dataForm.roleType = params;
    },
    // 新增
    submitForm: function() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            let params = Object.assign({}, this.dataForm);
            this.$api.role.saveFontRole(params).then(res => {
              this.editLoading = false;
              if (res.code == 200) {
                this.$message({ message: "操作成功", authType: "success" });
                this.dialogVisible = false;
                this.$refs["dataForm"].resetFields();
                this.roleType = "";
              } else {
                this.$message({
                  message: "操作失败, " + res.msg,
                  authType: "error"
                });
              }
              this.findPage(null);
            });
          });
        }
      });
    },
    // 编辑
    submitFormEdit: function() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            let params = Object.assign({}, this.dataForm);
            this.roleType_option.forEach(Ritem => {
              if (Ritem.value == params.roleType) {
                params.roleType = Ritem.key;
              }
            });
            
            this.$api.role.updateFontRole(params).then(res => {
              this.editLoading = false;
              if (res.result == 1) {
                this.$message({ message: res.msg, type: "success" });
                this.dialogVisible = false;
                this.$refs["dataForm"].resetFields();
                this.roleType = "";
              } else {
                this.$message({ message: res.msg, type: "error" });
              }
              this.findPage(null);
            });
          });
        }
      });
    },
    // 获取数据
    findTreeData: function() {
      this.menuLoading = true;
      this.$api.menu.findFontNavTree().then(res => {
        this.menuData = res.authorityList;
        this.menuLoading = false;
      });
    },
    // 树节点选择监听
    handleMenuCheckChange(data, check, subCheck) {
      if (check) {
        // 节点选中时同步选中父节点
        let parentId = data.parentId;
        this.$refs.menuTree.setChecked(parentId, true, false);
      } else {
        // 节点取消选中时同步取消选中子节点
        this.deleteTree(data);
      }
    },
    //树节点勾选全部子节点
    setChilds(data, node) {
      let arr = node.checkedKeys;
      if (arr.indexOf(data.id) != -1) {
        this.setTree(data);
      }
    },
    //递归方法
    setTree(data) {
      if (data.children != null) {
        data.children.forEach(element => {
          this.$refs.menuTree.setChecked(element.id, true, false);
          this.setTree(element);
        });
      }
    },
    deleteTree(data) {
      if (data.children != null) {
        data.children.forEach(element => {
          this.$refs.menuTree.setChecked(element.id, false, false);
          this.deleteTree(element);
        });
      }
    },
    // 重置选择
    resetSelection() {
      this.checkAll = false;
      this.$refs.menuTree.setCheckedKeys(this.dataForm.authorityList);
    },
    // 角色菜单授权提交
    submitAuthForm() {
      let checkedKeys = this.$refs.menuTree.getCheckedKeys(false);
      if (checkedKeys.length == 0) {
        this.$message({ message: "权限不能为空", type: "error" });
        return;
      }
      this.dataForm.authorityList = checkedKeys;
      this.power = false;
      this.dialogVisible = true;
    },
    // 新增
    submitForm: function() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            let params = Object.assign({}, this.dataForm);
            this.$api.role.saveFontRole(params).then(res => {
              this.editLoading = false;
              if (res.result == 1) {
                this.$message({ message: res.msg, type: "success" });
                this.dialogVisible = false;
                this.$refs["dataForm"].resetFields();
              } else {
                this.$message({ message: res.msg, type: "error" });
              }
              this.findPage(null);
            });
          });
        }
      });
    },
    renderContent(h, { node, data, store }) {
      return (
        <div class="column-container">
          <span style="text-algin:center;margin-right:80px;">
            {data.menuName}
          </span>
          <span style="text-algin:center;margin-right:80px;">
            <el-tag
              authType={
                data.authType === 0
                  ? ""
                  : data.authType === 1
                    ? "success"
                    : "info"
              }
              size="small"
            >
              {data.authType === 0
                ? "目录"
                : data.authType === 1
                  ? "菜单"
                  : "按钮"}
            </el-tag>
          </span>
          <span style="text-algin:center;margin-right:80px;">
            {" "}
            <i class={data.icon} />
          </span>
          <span style="text-algin:center;margin-right:80px;">
            {data.menuUrl ? data.menuUrl : "\t"}
          </span>
        </div>
      );
    }
  },
  updated: function() {
    var dialog = this.$children[1];
    if (dialog.rendered && this.power) {
      // console.log("update: " + $(".menu-container").html())
    }
  },
  mounted() {}
};
</script>
<style scoped>
.menu-container {
  margin-top: 10px;
}
.menu-header {
  padding-left: 8px;
  padding-bottom: 5px;
  text-align: left;
  font-size: 16px;
  color: rgb(20, 89, 121);
}
</style>
<style>
.rolemenu .el-dialog__footer {
  padding: 20px 20px 60px 20px;
}
.rolemenu .el-dialog__body {
  padding: 0px;
}
.role .el-dialog__wrapper .el-form-item__content {
  margin-left: 100px;
}
.role .el-form-item__content .el-input {
  width: 100%;
}
</style>
